import { ref } from 'vue';
import { defineStore } from 'pinia';
import { getDictSync } from '@/service/api/dict';

interface Store {
  [key: string]: any;
}

export const useDictStore = defineStore('dict', () => {
  const store = ref<Store>({});

  // 设置字典编码
  function SET_DICT(code: string, dict: any) {
    store.value[code] = dict;
  }

  // 获取字典编码
  async function GET_DICT(code: string) {
    if (store.value[code]) {
      return store.value[code];
    }
    const dict = await getDictSync(code);
    SET_DICT(code, dict);
    return dict;
  }

  //
  async function GET_DICT_BY_LIST(list: string[]) {
    // return Promise.all(list.map(code => GET_DICT(code))).then(res => {
    //   console.log(res);
    //   console.log(store);
    // });
    return new Promise(resolve => {
      Promise.all(list.map(code => GET_DICT(code))).then(res => {
        const obj: any = {};
        list.forEach((code, index) => {
          obj[code] = res[index];
        });
        resolve(obj);
      });
    });
  }

  // 重置字典
  function RESET_DICT() {
    store.value.dict = {};
  }

  return {
    store: store.value,
    setDict: SET_DICT,
    getDict: GET_DICT,
    getDictByList: GET_DICT_BY_LIST,
    resetDict: RESET_DICT
  };
});
